package org.yufan.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Service;
import org.yufan.bean.Item;
import org.yufan.bean.ItemDesc;
import org.yufan.service.BaseService;
import org.yufan.service.ItemDescService;
import org.yufan.service.ItemService;
import org.yufan.utils.HttpClientUtil;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;
import java.util.Date;

/**
 * Created by zxd on 2018/3/26.
 */
@Service
public class ItemServiceImpl extends BaseServiceImpl<Item> implements ItemService{
    @Autowired
    private ItemDescService itemDescService;

    @Autowired
    private JmsTemplate jmsTemplate;

    @Override
    public void addItem(Item item, String desc) {
        //设置商品为下架
        item.setStatus(2);
        //保存商品信息
        item.setCreated(new Date());
        item.setUpdated(item.getCreated());
        this.save(item);
        ItemDesc itemDesc=new ItemDesc();
        itemDesc.setItemId(item.getId());
        itemDesc.setItemDesc(desc);
        itemDesc.setCreated(item.getCreated());
        itemDesc.setUpdated(item.getCreated());
        //保存描述信息
        itemDescService.save(itemDesc);
    }

    @Override
    public void updateItem(Item item, String desc) {
        //修改商品信息
        item.setUpdated(new Date());
        this.update(item);
        //修改描述信息
        ItemDesc itemDesc=new ItemDesc();
        itemDesc.setItemId(item.getId());
        itemDesc.setItemDesc(desc);
        itemDesc.setUpdated(item.getUpdated());
        itemDescService.update(itemDesc);

        //传统方案
        //调用前台接口删除缓存
       // HttpClientUtil.doGet("http://www.yufan.com/rpc/item/cache/delete/"+
         //       item.getId());
        //TODO 判断，如果缓存没有删除怎么办?

        //使用mq  通知消费者
        //生产消息
        jmsTemplate.send(new MessageCreator() {
            @Override
            public Message createMessage(Session session) throws JMSException {
                return session.createTextMessage(String.valueOf(item.getId()));
            }
        });

    }
}
